import { prisma } from "../database/generated/prisma-client";
import logger from "./log";
import { blkGraphqlFragment } from "./utils";

class BlockObserver {
    constructor(courier, subscriber) {
        this.courier = courier;
        this.subscriber = subscriber;
    }

    isMatched(block) {
        const { startingBlockHeight = 1, endingBlockHeight = null } = this.subscriber;
        const height = block.HEADER.HEIGHT;
        if (startingBlockHeight && endingBlockHeight) {
            return (height >= startingBlockHeight && height <= endingBlockHeight );
        }
        if (startingBlockHeight) {
            return height >= startingBlockHeight;
        }
        if (endingBlockHeight) {
            return height <= endingBlockHeight;
        }
        return true;
    }

    update(block) {
        const height = block.HEADER.HEIGHT;
        logger.info(`For subscriber ${this.subscriber.name}: observed the new block(height=${height})`);
        const { startingBlockHeight = 1, endingBlockHeight = null } = this.subscriber;
        if (!this.isMatched(block)) {
            const msg1 = `For subscriber ${this.subscriber.name}: `;
            const msg2 = `the new block(height=${height}) is not matched with the range`;
            const msg3 = `(${startingBlockHeight}-${endingBlockHeight}), `;
            logger.info(`${msg1}${msg2}${msg3}`);
            return;
        }
        prisma.block({id: block.id}).$fragment(blkGraphqlFragment).then((blk) => this.courier.handleNewBlock(blk));
    }
}

export default BlockObserver;